package com.ly.emp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ly.common.core.bean.R;
import com.ly.common.core.bean.vo.TreeVO;
import com.ly.common.core.exception.ServiceException;
import com.ly.common.core.utils.BaseUtils;
import com.ly.emp.bean.dto.HubTeamDTO;
import com.ly.emp.bean.dto.PluraOrgDTO;
import com.ly.emp.bean.vo.BaseSuitunitOrgTreeVO;
import com.ly.emp.constant.EmpErrorConstants;
import com.ly.emp.entity.EpmBaseRel;
import com.ly.emp.entity.EpmBaseSuitunit;
import com.ly.emp.entity.EpmBaseSuitunitOrg;
import com.ly.emp.entity.EpmTeamConversionMode;
import com.ly.emp.enums.HubSuitUnitRelPersonTypeEnum;
import com.ly.emp.service.*;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 班组公共服务-impl
 *
 * @author luoyun
 * @Date: 2025/5/13 14:37
 * @Note:
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class EmpCommonServiceImpl implements IEmpCommonService {

    private final IEpmBaseSuitunitService baseSuitunitService;
    private final IEpmBaseSuitunitOrgService baseSuitunitOrgService;
    private final IEpmBaseRelService baseRelService;
    private final IEpmTeamConversionModeService teamConversionModeService;

    @Override
    public R<List<EpmBaseSuitunitOrg>> getPluraList(String type) {
        EpmBaseSuitunitOrg entity = new EpmBaseSuitunitOrg();
        entity.setIsAssess("true");
        entity.setOrgType("4");
        String workNum = BaseUtils.getWorkNum();
        if (workNum == null) {
            return R.ok();
        }
        if ("1".equals(type)) {
            entity.setPsnNum(workNum);
        } else {
            entity.setPluraList(workNum);
        }
        return R.ok(baseSuitunitOrgService.getListByEntity(entity));
    }

    @Override
    public R<List<EpmTeamConversionMode>> getConversionModeList() {
        List<EpmTeamConversionMode> list = teamConversionModeService.list(
                new LambdaQueryWrapper<EpmTeamConversionMode>()
                        .orderByAsc(EpmTeamConversionMode::getDisplayOrder));
        return R.ok(list);
    }

    @Override
    public R<List<EpmBaseRel>> getBaseRelList(String type, String orgCode) {
        List<EpmBaseRel> baseRelList = this.getBaseRelListByOrgCode(type, orgCode);
        return R.ok(baseRelList);
    }

    @Override
    public EpmBaseRel getBaseRelByParam(EpmBaseRel entity) {
        String type = "true";
        String orgCode = entity.getOrgCode();
        if (StrUtil.isNotEmpty(orgCode)) {
            List<String> isIntensificationList = this.getIsIntensificationListByOrgCode(orgCode);
            entity.setOrgCodeList(isIntensificationList);
            entity.setOrgCode(null);
        }
        List<EpmBaseRel> list = baseRelService.getListByEntity(entity);
        if (CollUtil.isEmpty(list)) {
            return null;
        }
        EpmBaseRel baseRel = list.get(0);
        return baseRel;
    }

    /**
     * 班组人员列表-内部接口调用
     *
     * @param type    ： "true":考核  "false":不考核
     * @param orgCode
     * @return
     */
    @Override
    public List<EpmBaseRel> getBaseRelListByOrgCode(String type, String orgCode) {
        if (StrUtil.isBlank(orgCode)) {
            throw new ServiceException(EmpErrorConstants.NO_TEAM);
        }
        // 不传，则默认查询需要考核的人员
        if (StrUtil.isBlank(type)) {
            type = "true";
        }
        EpmBaseRel entity = new EpmBaseRel();
        List<String> isIntensificationList = this.getIsIntensificationListByOrgCode(orgCode);
        entity.setOrgCodeList(isIntensificationList);
        entity.setPersonType(HubSuitUnitRelPersonTypeEnum.b6.getCode());
        entity.setIsAssess(type);
        List<EpmBaseRel> baseRelList = baseRelService.getListByEntity(entity);
        if (CollUtil.isNotEmpty(baseRelList)) {
            // 统一排序和人员类型
            for (int i = 0; i < baseRelList.size(); i++) {
                EpmBaseRel baseRel = baseRelList.get(i);
                baseRel.setDisplayOrder(i + "");
            }
        }
        return baseRelList;
    }

    @Override
    public String[] getDropdownPsnNameDatas(HubTeamDTO dto) {
        String orgCode = dto.getOrgCode();
        if (StrUtil.isBlank(orgCode)) {
            throw new ServiceException(EmpErrorConstants.NO_TEAM);
        }
        String type = "true";
        EpmBaseRel entity = new EpmBaseRel();
        List<String> isIntensificationList = this.getIsIntensificationListByOrgCode(orgCode);
        entity.setOrgCodeList(isIntensificationList);
        entity.setPersonType(HubSuitUnitRelPersonTypeEnum.b6.getCode());
        entity.setIsAssess(type);
        List<EpmBaseRel> baseRelList = baseRelService.getListByEntity(entity);
        String[] resNames = {};
        if (CollUtil.isNotEmpty(baseRelList)) {
            List<String> psnNameList = baseRelList.stream().map(EpmBaseRel::getPsnName).collect(Collectors.toList());
            return psnNameList.toArray(new String[psnNameList.size()]);
        }
        return resNames;
    }

    @Override
    public List<EpmBaseSuitunitOrg> getBaseSuitunitOrgListByRole(List<String> orgList) {
        String suitUnit = BaseUtils.getSuitUnit();
        if (StrUtil.isBlank(suitUnit)) {
            return null;
        }
        PluraOrgDTO dto = new PluraOrgDTO();
        dto.setSuitUnit(suitUnit);
        dto.setTypeFlag(false);
        dto.setOrgCodeList(orgList);
        return baseSuitunitOrgService.getPluraTeamList(dto);
    }

    @Override
    public EpmBaseSuitunitOrg getBaseSuitunitOrgByOrgCode(String orgCode) {
        EpmBaseSuitunitOrg entity = new EpmBaseSuitunitOrg();
        entity.setOrgCode(orgCode);
        List<EpmBaseSuitunitOrg> list = baseSuitunitOrgService.getListByEntity(entity);
        return CollUtil.isNotEmpty(list) ? list.get(0) : null;
    }

    @Override
    public List<String> getIsIntensificationListByOrgCode(String orgCode) {
        List<String> orgList = new ArrayList<>();
        // 集约化处理
        EpmBaseSuitunitOrg baseSuitunitOrg = baseSuitunitOrgService.getOne(
                new LambdaQueryWrapper<EpmBaseSuitunitOrg>()
                        .eq(EpmBaseSuitunitOrg::getOrgCode, orgCode)
        );
        if (baseSuitunitOrg != null && "2".equals(baseSuitunitOrg.getIsIntensificationFlag())) {
            String isIntensificationStr = baseSuitunitOrg.getIsIntensificationList();
            orgList = (List<String>) JSONArray.parseArray(isIntensificationStr, String.class);
        } else {
            orgList.add(orgCode);
        }
        return orgList;
    }

    @Override
    public List<EpmBaseSuitunitOrg> getBaseSuitunitOrgByOrgCodeList(List<String> isIntensificationList) {
        EpmBaseSuitunitOrg entity = new EpmBaseSuitunitOrg();
        entity.setOrgList(isIntensificationList);
        return baseSuitunitOrgService.getListByEntity(entity);
    }

    @Override
    public R getBaseRelTree(String type, String orgCode) {
        List<EpmBaseRel> baseRelList = this.getBaseRelListByOrgCode(type, orgCode);
        List<TreeVO> vos = baseRelList.stream()
                .map(n -> new TreeVO(n.getPsnNum(), n.getPsnName(), null))
                .collect(Collectors.toList());
        return R.ok(vos);
    }

    @Override
    public R findTree() {
        String suitUnit = BaseUtils.getSuitUnit();
        if (StrUtil.isBlank(suitUnit)) {
            return R.fail("找不到考核单位信息");
        }
        List<EpmBaseSuitunitOrg> allSuitunitOrgList = baseSuitunitOrgService.list(
                new LambdaQueryWrapper<EpmBaseSuitunitOrg>()
                        .eq(EpmBaseSuitunitOrg::getSuitUnit, suitUnit)
                        .orderByAsc(EpmBaseSuitunitOrg::getOrgCode)
        );
        List<BaseSuitunitOrgTreeVO> allVo = BeanUtil.copyToList(allSuitunitOrgList, BaseSuitunitOrgTreeVO.class);
        List<BaseSuitunitOrgTreeVO> vos = this.getTree(allVo);
        // 封装顶级目录
        EpmBaseSuitunit one = baseSuitunitService.getOne(
                new LambdaQueryWrapper<EpmBaseSuitunit>()
                        .eq(EpmBaseSuitunit::getOrgCode, suitUnit)
        );
        BaseSuitunitOrgTreeVO p = BeanUtil.copyProperties(one, BaseSuitunitOrgTreeVO.class);
        p.setChildren(vos);
        List<BaseSuitunitOrgTreeVO> voss = new ArrayList<>();
        voss.add(p);
        return R.ok(voss);
    }

    /**
     * 任意递归-组装节点的树形数据
     *
     * @param allList
     * @return
     */
    private List<BaseSuitunitOrgTreeVO> getTree(List<BaseSuitunitOrgTreeVO> allList) {
        List<BaseSuitunitOrgTreeVO> vos = new ArrayList<>();
        // 所有父级map，key为组织编码，value为组织对象
        Map<String, BaseSuitunitOrgTreeVO> map =
                allList.stream().collect(Collectors.toMap(BaseSuitunitOrgTreeVO::getOrgCode, o -> o, (n1, n2) -> n1));
        // 实现树形结构
        allList.stream().forEach(vo -> {
            BaseSuitunitOrgTreeVO parent = map.get(vo.getParentOrgCode());
            if (ObjectUtils.isEmpty(parent)) {
                vos.add(vo);
            } else {
                Collection<BaseSuitunitOrgTreeVO> children = parent.getChildren();
                if (CollUtil.isEmpty(children)) {
                    parent.setChildren(new ArrayList<>());
                }
                // 此处不能用  children.add(vo); 否则孩子为空
                parent.getChildren().add(vo);
            }
        });
        return vos;
    }
}
